import {PlayerModel} from "../../../database/models/player";
import PrizeRecord from '../../../database/models/prizeRecord'

export const typeDefs = `
  
  type PrizePlayerRecord {
    _id: String!,
    name:String!,
    headImgUrl: String
  }

  type PrizeRecord{
    _id: String
    prizeName: String!
    prizeImageUrl:String!
    player:Player
    playerShortId: String!
    state: String!
    createAt: String!
  } 
`

export const queryDefs = `
  getPrizeRecords(page:Int, playerId:String): [PrizeRecord]!
  getPrizeRecordByShortId(shortId:Int!): [PrizeRecord]!
  prizeRecordByPlayer(playerId:String!): [PrizeRecord]!
`

export const mutationDefs = `
  deliverPrizeRecords(
    _id: String!
  ):PrizeRecord!    
`

export const resolvers = {
  Query: {
    async getPrizeRecords(_, {page = 0, playerId = ''}) {
      const condition = playerId ? {playerShortId: playerId} : {}

      const records = await PrizeRecord.find(condition)
        .sort({_id: -1})
        .skip(page * 10)
        .limit(10)
        .lean()
      return records
    },

    async prizeRecordByPlayer(_, {playerId}) {
      const records = await PrizeRecord.find({player: playerId})
        .sort({createAt: -1})
        .lean()
      return records
    },

    async getPrizeRecordByShortId(_, {shortId}) {
      const records = await PrizeRecord.find({playerShortId: shortId})
        .sort({_id: -1})
        .lean()
      return records
    }
  },

  Mutation: {
    async deliverPrizeRecords(_, {_id}) {
      const record = await PrizeRecord.findOne({_id}).populate('player')

      if (!record) {
        throw Error('没有此商品')
      }
      record.state = 'Done'
      await record.save()

      return record.toObject()
    }
  },

  PrizeRecord: {
    async player({player}) {
      const p = await PlayerModel.findById(player)
      if (p) {
        return p
      } else {
        return {_id: player}
      }
    }

  }


}
